package com.yingxin.yxerp.module.common.util;

import cn.hutool.core.date.DateUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TimeDiffUtil {

    private static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM");
    private static Calendar calendar=Calendar.getInstance();


    public static Integer getTimeDiffToMinutes(Date startTime, Date endTime) {
        long endMs = endTime.getTime();
        long startMs = startTime.getTime();
        return Math.toIntExact((endMs - startMs) / 1000 / 60);
    }

    public static Integer getTimeDiffToDays(Date startTime, Date endTime) {
        long endMs = endTime.getTime();
        long startMs = startTime.getTime();
        return Math.toIntExact((endMs - startMs) / 1000 / 60 / 60 /24);
    }

    /*
         输入日期字符串比如201703，返回当月第一天的Date
      */
    public static Date getMinDateMonth(String month){
        try {
            Date nowDate=sdf.parse(month);
            calendar = Calendar.getInstance();
            calendar.setTime(nowDate);
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
            return DateUtil.beginOfDay(calendar.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
           输入日期字符串，返回当月最后一天的Date
       */
    public static Date getMaxDateMonth(String month){
        try {
            Date nowDate=sdf.parse(month);
            calendar = Calendar.getInstance();
            calendar.setTime(nowDate);
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            return DateUtil.endOfDay(calendar.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws ParseException{
        String month="2017-05";
        System.out.println(getMinDateMonth(month));
        System.out.println(getMaxDateMonth(month));
    }

}
